import pandas as pd
from typing import Dict, List

from interfaces.transformers import ILbup
from interfaces.form_metadata import IFormMetadataProvider
from constants import SUBJECT_NUMBER, FormAllConstants, BASE_COLS
from common.pivot.default_period_pivot import PeriodPivotHelper


class LbupTransformer(ILbup):
    def __init__(self, default_source_data: str, metadata: IFormMetadataProvider):
        self.default_source_data = default_source_data
        self.metadata = metadata
        self.helper = PeriodPivotHelper(default_source_data)

    def process_lbup(self, all_results: Dict[str, pd.DataFrame]) -> None:
        lbup_oids: List[str] = self.metadata.get_targets((FormAllConstants.IsLbup, True), FormAllConstants.ModuleOID, True)
        if not lbup_oids:
            return

        lbup_results: Dict[str, pd.DataFrame] = {}
        for oid in lbup_oids:
            # 使用通用帮助器，按“行号之后的所有列”扩展
            result = self.helper.build(
                sheet_name=oid,
                base_cols=BASE_COLS + ['LBSCAT'],
                merge_keys=[SUBJECT_NUMBER, 'LBSCAT'],
                period_column='LBREAS',
                screening_value='筛选期检查',
                outgroup_value='出组检查',
                screening_prefix='筛选期检查',
                outgroup_prefix='出组检查',
                expand_after_line_number=True,
            )
            if result is None or result.empty:
                continue
            lbup_results[oid + 'IsLbup'] = result

        if lbup_results:
            combined_lbup = pd.concat(lbup_results.values(), axis=0, ignore_index=True, join='outer').fillna("")
            all_results['lbup关键指标'] = combined_lbup